<template>
  <!-- 封装日历组件 -->
  <div class="calendar_wrapper">
    <div class="calendar" :class="{ active: visible }">
      <div class="calendar_header">
        <div class="calendar_header_title">日期选择</div>
        <div class="calendar_header_close" @click="close">
          <Icon name="close" color="#ccc"></Icon>
        </div>
      </div>
      <!-- 日历时间 -->
      <!-- 日历时间 -->
      <div class="calendar_time">
        <div class="calendar_time_year">{{ currentTimeYear }}</div>
        <div class="calendar_time_month">{{ currentTimeMonth }}</div>
      </div>
      <!-- 日历星期 -->
      <div class="calendar_week">
        <div>日</div>
        <div>一</div>
        <div>二</div>
        <div>三</div>
        <div>四</div>
        <div>五</div>
        <div>六</div>
      </div>
      <!-- 日历主体 -->
      <!-- 日历主体 -->
      <div class="calendar_body">
        <div
          class="calendar_body_item"
          v-for="m in months"
          :key="`${m.year}-${m.month}`"
          ref="monthItems"
        >
          <!-- 月份标题 -->
          <div class="calendar_body_item_data_title">
            {{ m.title }}
          </div>

          <!-- 日历列表 -->
          <div class="calendar_body_item_data_list">
            <div
              class="calendar_body_item_data"
              v-for="(day, index) in m.days"
              :key="index"
              :class="{
                active: day !== null && isToday(m.year, m.month, day),
                selected: day !== null && isSelected(m.year, m.month, day),
              }"
              @click="day !== null && selectDate(m.year, m.month, day)"
            >
              {{ day }}
            </div>
          </div>
        </div>
      </div>
      <!-- 底部按钮 -->
      <div class="calendar_footer">
        <div class="calendar_footer_btn" @click="handleConfirm">确定</div>
      </div>
    </div>
    <!-- 遮罩层 -->
    <div
      class="calendar_mask"
      :class="{ active: visible }"
      @click="close"
    ></div>
  </div>
</template>

<script>
import Icon from '@/components/common/Icon/index.vue';

export default {
  components: {
    Icon,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      months: [], // 存储要显示的月份数据
      currentVisibleMonth: null, // 当前可见的月份对象
      currentTimeYear: '', // 显示在顶部的年
      currentTimeMonth: '', // 显示在顶部的月
      selectedDate: null, // 存储用户选择的日期 { year, month, day }
    };
  },
  mounted() {
    this.generatePastMonths(8);
    this.$nextTick(() => {
      this.initScrollObserver();
      this.scrollToCurrentMonth();
    });
  },
  methods: {
    close() {
      this.$emit('close');
    },
    // 获取某月的总天数
    getDaysInMonth(year, month) {
      return new Date(year, month + 1, 0).getDate();
    },
    // 获取某月1号是星期几 (0-6, 0=周日)
    getStartDayOfWeek(year, month) {
      return new Date(year, month, 1).getDay();
    },
    // 生成 n 个过去的月份（包括当前月），按时间升序排列（从旧到新）
    generatePastMonths(count) {
      const months = [];
      const today = new Date();
      const currentYear = today.getFullYear();
      const currentMonth = today.getMonth();

      for (let i = count - 1; i >= 0; i--) {
        const date = new Date(currentYear, currentMonth - i);
        const year = date.getFullYear();
        const month = date.getMonth();
        const monthNumber = date.toLocaleDateString('zh-CN', {
          month: 'numeric',
        });

        const daysInMonth = this.getDaysInMonth(year, month);
        const startDay = this.getStartDayOfWeek(year, month);

        const days = [];
        for (let j = 0; j < startDay; j++) days.push(null);
        for (let day = 1; day <= daysInMonth; day++) days.push(day);

        months.push({
          year,
          month,
          days,
          title: `${year}年${monthNumber}`,
          displayYear: `${year}年`,
          displayMonth: `${monthNumber}`,
        });
      }

      this.months = months;

      // 初始化顶部显示为当前月
      const current = months[months.length - 1];
      this.currentTimeYear = current.displayYear;
      this.currentTimeMonth = current.displayMonth;
    },

    // 判断是否是今天
    isToday(year, month, day) {
      const today = new Date();
      return (
        today.getFullYear() === year &&
        today.getMonth() === month &&
        today.getDate() === day
      );
    },
    initScrollObserver() {
      const observer = new IntersectionObserver(
        entries => {
          // 找出当前最接近视口顶部且可见的月份
          const visible = entries
            .filter(entry => entry.isIntersecting)
            .sort(
              (a, b) => a.boundingClientRect.top - b.boundingClientRect.top
            );

          if (visible.length > 0) {
            const target = visible[0].target;
            const index = Array.from(this.$refs.monthItems).indexOf(target);
            const monthData = this.months[index];

            if (monthData) {
              this.currentTimeYear = `${monthData.year}年`;
              this.currentTimeMonth = `${monthData.month + 1}月`; // getMonth() 是 0-based
            }
          }
        },
        {
          root: this.$el.querySelector('.calendar_body'),
          threshold: 0.5, // 至少50%可见才触发
          rootMargin: '0px',
        }
      );

      this.$refs.monthItems.forEach(el => observer.observe(el));
    },
    scrollToCurrentMonth() {
      this.$nextTick(() => {
        const body = this.$el.querySelector('.calendar_body');
        body.scrollTop = body.scrollHeight; // 滚到底部
      });
    },
    // 选择日期
    selectDate(year, month, day) {
      this.selectedDate = { year, month, day };
    },
    // 判断是否已选
    isSelected(year, month, day) {
      if (!this.selectedDate) return false;
      return (
        this.selectedDate.year === year &&
        this.selectedDate.month === month &&
        this.selectedDate.day === day
      );
    },
    // 点击确定按钮
    handleConfirm() {
      if (!this.selectedDate) {
        // 未选择，默认为今天
        const today = new Date();
        this.selectedDate = {
          year: today.getFullYear(),
          month: today.getMonth(),
          day: today.getDate(),
        };
      }

      // 格式化为 2025-9-9
      const dateStr = `${this.selectedDate.year}-${
        this.selectedDate.month + 1
      }-${this.selectedDate.day}`;

      // 触发事件给父组件
      this.$emit('confirm', dateStr);

      // 可选：关闭日历
      this.$emit('update:visible', false);
    },
    // 关闭弹窗
    close() {
      this.$emit('update:visible', false);
    },
  },
};
</script>

<style lang="scss">
.calendar_wrapper {
  .calendar {
    position: fixed;
    width: 100%;
    height: 78%;
    background-color: #fff;
    bottom: 0;
    left: 0;
    z-index: 2000;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    display: flex;
    flex-direction: column;
    transform: translateY(100%);
    transition: all 0.3s ease-in-out;

    &.active {
      transform: translateY(0);
    }
    .calendar_header {
      flex-shrink: 0; // 不压缩
      padding: 24px;
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: bold;
      color: #333;
      border-bottom: 1px solid #ccc;
      position: relative;

      .calendar_header_title {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        font-size: 16px;
      }

      .calendar_header_close {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .calendar_time {
      flex-shrink: 0; // 不压缩
      padding: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      color: #333;
      font-weight: bold;
    }

    .calendar_week {
      flex-shrink: 0; // 不压缩
      padding: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      color: #333;
      font-weight: bold;
      // 底部阴影
      box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
    }

    .calendar_body {
      flex: 1;
      font-size: 14px;
      color: #333;
      font-weight: bold;
      // 可滚动
      overflow-y: auto;

      // 隐藏滚动条
      &::-webkit-scrollbar {
        display: none;
      }

      .calendar_body_item {
        width: 100%;
        .calendar_body_item_data_title {
          width: 100%;
          padding: 18px 10px 10px 10px;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .calendar_body_item_data_list {
          display: flex;
          flex-wrap: wrap;
          gap: 4px; // 更好的间距控制

          .calendar_body_item_data {
            width: calc(100% / 7 - 4px); // 考虑 gap
            aspect-ratio: 1 / 1; // 正方形日期格子
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.3s ease-in-out;
            font-weight: bold;

            &.active {
              background-color: #ef0924;
              color: #fff;
            }

            &.selected {
              background-color: #007aff; // 蓝色
              color: #fff;
            }

            &:first-child {
              margin-left: 50px;
            }
          }
        }
      }
    }

    .calendar_footer {
      flex-shrink: 0; // 不压缩
      padding: 16px;
      background-color: #fff;
      border-top: 1px solid #eee;

      .calendar_footer_btn {
        width: 80%;
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-radius: 20px;
        background-color: #ef0924;
        color: #fff;
        font-size: 16px;
        font-weight: bold;
        margin: 0 auto;
      }
    }
  }

  .calendar_mask {
    position: fixed;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    top: 0;
    left: 0;
    z-index: 1000;
    visibility: hidden;
    opacity: 0;
    transition: all 0.3s ease-in-out;

    &.active {
      visibility: visible;
      opacity: 1;
    }
  }
}
</style>
